package com.farmer.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.DonationRecord;
import com.farmer.common.entity.Project;
import com.farmer.common.result.Result;
import com.farmer.project.dto.DonationDTO;
import com.farmer.project.mapper.DonationRecordMapper;
import com.farmer.project.mapper.ProjectMapper;
import com.farmer.project.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 扶贫项目服务实现类
 */
@Slf4j
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private DonationRecordMapper donationRecordMapper;

    @Override
    public Result<?> getProjectList(Integer pageNum, Integer pageSize, String status, String keyword) {
        try {
            Page<Project> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Project> queryWrapper = new QueryWrapper<>();

            // 状态过滤
            if (StringUtils.hasText(status)) {
                queryWrapper.eq("status", status);
            }

            // 关键词搜索（标题、描述、地点）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                        .like("title", keyword)
                        .or()
                        .like("description", keyword)
                        .or()
                        .like("location", keyword)
                );
            }

            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");

            Page<Project> projectPage = projectMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", projectPage.getRecords());
            result.put("total", projectPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取扶贫项目列表成功", result);
        } catch (Exception e) {
            log.error("获取扶贫项目列表失败：{}", e.getMessage(), e);
            return Result.error("获取扶贫项目列表失败");
        }
    }

    @Override
    public Result<?> getProjectById(Long projectId) {
        try {
            if (projectId == null) {
                return Result.error("项目ID不能为空");
            }

            Project project = projectMapper.selectById(projectId);
            if (project == null) {
                return Result.error("项目不存在");
            }

            return Result.success("获取项目详情成功", project);
        } catch (Exception e) {
            log.error("获取项目详情失败：{}", e.getMessage(), e);
            return Result.error("获取项目详情失败");
        }
    }

    @Override
    public Result<?> addProject(Project project) {
        try {
            if (project == null) {
                return Result.error("项目信息不能为空");
            }

            // 基本验证
            if (!StringUtils.hasText(project.getTitle())) {
                return Result.error("项目标题不能为空");
            }
            if (!StringUtils.hasText(project.getDescription())) {
                return Result.error("项目描述不能为空");
            }
            if (project.getTargetAmount() == null || project.getTargetAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("目标金额必须大于0");
            }

            // 设置默认值
            if (project.getCurrentAmount() == null) {
                project.setCurrentAmount(BigDecimal.ZERO);
            }
            if (project.getDonorCount() == null) {
                project.setDonorCount(0);
            }
            if (!StringUtils.hasText(project.getStatus())) {
                project.setStatus("ACTIVE");
            }

            int result = projectMapper.insert(project);
            if (result > 0) {
                log.info("添加扶贫项目成功：{}", project.getTitle());
                return Result.success("添加项目成功");
            } else {
                return Result.error("添加项目失败");
            }
        } catch (Exception e) {
            log.error("添加扶贫项目失败：{}", e.getMessage(), e);
            return Result.error("添加项目失败");
        }
    }

    @Override
    public Result<?> updateProject(Project project) {
        try {
            if (project == null || project.getId() == null) {
                return Result.error("项目信息不能为空");
            }

            // 检查项目是否存在
            Project existProject = projectMapper.selectById(project.getId());
            if (existProject == null) {
                return Result.error("项目不存在");
            }

            int result = projectMapper.updateById(project);
            if (result > 0) {
                log.info("更新扶贫项目成功：{}", project.getTitle());
                return Result.success("更新项目成功");
            } else {
                return Result.error("更新项目失败");
            }
        } catch (Exception e) {
            log.error("更新扶贫项目失败：{}", e.getMessage(), e);
            return Result.error("更新项目失败");
        }
    }

    @Override
    @Transactional
    public Result<?> donateToProject(DonationDTO donationDTO) {
        try {
            // 验证项目是否存在
            Project project = projectMapper.selectById(donationDTO.getProjectId());
            if (project == null) {
                return Result.error("项目不存在");
            }

            // 验证项目状态
            if (!"ACTIVE".equals(project.getStatus())) {
                return Result.error("项目当前不接受捐赠");
            }

            // 创建捐赠记录
            DonationRecord donationRecord = new DonationRecord();
            donationRecord.setProjectId(donationDTO.getProjectId());
            donationRecord.setUserId(donationDTO.getUserId());
            donationRecord.setAmount(donationDTO.getAmount());
            donationRecord.setDonorName(donationDTO.getDonorName());
            donationRecord.setMessage(donationDTO.getMessage());
            donationRecord.setIsAnonymous(donationDTO.getIsAnonymous() != null ? donationDTO.getIsAnonymous() : 0);
            donationRecord.setPaymentMethod(donationDTO.getPaymentMethod());
            donationRecord.setTransactionNo(UUID.randomUUID().toString());
            donationRecord.setStatus("SUCCESS");

            int donationResult = donationRecordMapper.insert(donationRecord);
            if (donationResult <= 0) {
                throw new RuntimeException("创建捐赠记录失败");
            }

            // 更新项目筹款金额和捐赠人数
            BigDecimal newCurrentAmount = project.getCurrentAmount().add(donationDTO.getAmount());
            Integer newDonorCount = project.getDonorCount() + 1;

            project.setCurrentAmount(newCurrentAmount);
            project.setDonorCount(newDonorCount);

            // 检查是否达到目标金额
            if (newCurrentAmount.compareTo(project.getTargetAmount()) >= 0) {
                project.setStatus("COMPLETED");
            }

            int projectResult = projectMapper.updateById(project);
            if (projectResult <= 0) {
                throw new RuntimeException("更新项目信息失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("donationId", donationRecord.getId());
            result.put("transactionNo", donationRecord.getTransactionNo());
            result.put("currentAmount", newCurrentAmount);
            result.put("donorCount", newDonorCount);

            log.info("项目捐赠成功，项目ID：{}，金额：{}", donationDTO.getProjectId(), donationDTO.getAmount());
            return Result.success("捐赠成功", result);

        } catch (Exception e) {
            log.error("项目捐赠失败：{}", e.getMessage(), e);
            return Result.error("捐赠失败：" + e.getMessage());
        }
    }

    @Override
    public Result<?> getDonationList(Long projectId, Integer pageNum, Integer pageSize) {
        try {
            if (projectId == null) {
                return Result.error("项目ID不能为空");
            }

            Page<DonationRecord> page = new Page<>(pageNum, pageSize);
            QueryWrapper<DonationRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_id", projectId);
            queryWrapper.eq("status", "SUCCESS");
            queryWrapper.orderByDesc("create_time");

            Page<DonationRecord> donationPage = donationRecordMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", donationPage.getRecords());
            result.put("total", donationPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取捐赠记录成功", result);
        } catch (Exception e) {
            log.error("获取捐赠记录失败：{}", e.getMessage(), e);
            return Result.error("获取捐赠记录失败");
        }
    }

    @Override
    public Result<?> getUserDonationList(Long userId, Integer pageNum, Integer pageSize) {
        try {
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            Page<DonationRecord> page = new Page<>(pageNum, pageSize);
            QueryWrapper<DonationRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("status", "SUCCESS");
            queryWrapper.orderByDesc("create_time");

            Page<DonationRecord> donationPage = donationRecordMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", donationPage.getRecords());
            result.put("total", donationPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取用户捐赠记录成功", result);
        } catch (Exception e) {
            log.error("获取用户捐赠记录失败：{}", e.getMessage(), e);
            return Result.error("获取用户捐赠记录失败");
        }
    }

    @Override
    public Result<?> getProjectStatistics() {
        try {
            // 统计项目总数
            Long totalProjects = projectMapper.selectCount(null);

            // 统计各状态项目数量
            Map<String, Long> statusCount = new HashMap<>();
            QueryWrapper<Project> activeQuery = new QueryWrapper<>();
            activeQuery.eq("status", "ACTIVE");
            Long activeCount = projectMapper.selectCount(activeQuery);
            statusCount.put("ACTIVE", activeCount);

            QueryWrapper<Project> completedQuery = new QueryWrapper<>();
            completedQuery.eq("status", "COMPLETED");
            Long completedCount = projectMapper.selectCount(completedQuery);
            statusCount.put("COMPLETED", completedCount);

            // 统计总筹款金额
            QueryWrapper<DonationRecord> donationQuery = new QueryWrapper<>();
            donationQuery.select("SUM(amount) as total_amount");
            donationQuery.eq("status", "SUCCESS");
            Map<String, Object> donationStats = donationRecordMapper.selectMaps(donationQuery).get(0);

            BigDecimal totalDonation = BigDecimal.ZERO;
            if (donationStats.get("total_amount") != null) {
                totalDonation = (BigDecimal) donationStats.get("total_amount");
            }

            // 统计总捐赠人次
            Long totalDonors = donationRecordMapper.selectCount(new QueryWrapper<DonationRecord>().eq("status", "SUCCESS"));

            Map<String, Object> result = new HashMap<>();
            result.put("totalProjects", totalProjects);
            result.put("statusCount", statusCount);
            result.put("totalDonation", totalDonation);
            result.put("totalDonors", totalDonors);

            return Result.success("获取项目统计成功", result);
        } catch (Exception e) {
            log.error("获取项目统计失败：{}", e.getMessage(), e);
            return Result.error("获取项目统计失败");
        }
    }

    @Override
    public Result<?> deleteProjectById(Long projectId) {
        // 检查项目是否存在
        Project project = projectMapper.selectById(projectId);
        if (project == null) {
            return Result.error("项目不存在");
        }

        // 执行删除操作
        projectMapper.deleteById(projectId);
        return Result.success("项目删除成功");
    }
} 